<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form-model layout="inline" ref="ruleForm" :model="queryParam">
          <z-form-item
            :datas="fieldArr"
            :form="queryParam"
            :submitAction="{show: true, toggle: true, span: 6}"
            @change="getChangeTime"
            @onSubmit="onQuery"
            @onReset="onResetForm"
          />
        </a-form-model>
      </div>
    </a-card>
    <a-card :bordered="false">
      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <div>
          <a-button type="primary" @click="clickPush()">新建</a-button>
          <a-button :disabled="isDisabled" @click="handleOperate('enable')">启用</a-button>
          <a-button :disabled="isDisabled" @click="handleOperate('disable')">停用</a-button>
        </div>
      </div>
      <!-- 表格展示 -->
      <div class="table-page-content">
        <z-table
          ref="table"
          rowKey="keyWordId"
          :showAlert="false"
          :showSelection="true"
          :loading="loading"
          :columns="columns"
          :dataSource="pageData"
          @selectedRow="onSelectedRow"
          @change="onTableChange"
        />
      </div>
    </a-card>
    <j-modal
      :title="title"
      :width="600"
      :visible="visible"
      switchFullscreen
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭">
      <a-form-model layout="horizontal" ref="subForm" :model="model" :rules="validatorRules" v-bind="formItemLayout">
        <z-form-item :datas="fieldArrModal" :form="model" :rules="validatorRules" :gutter="0" />
      </a-form-model>
    </j-modal>
  </div>
</template>

<script>
import * as alarmServiceApi from '@/api/sjsk/alarmService'
export default {
  data() {
    return {
      loading: false,
      isDisabled: true,
      queryParam: {},
      title: '新建',
      model: {},
      visible: false,
      confirmLoading: false,
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 }
      },
      fieldArr: [
        { label: '关键词', prop: 'keyWordName', tagType: 'input', span: 8 },
        { label: '关键词级别', prop: 'keyWordLevel', tagType: 'dict-select', dictCode: 'keyword_level', span: 8 },
        { label: '关键词类别', prop: 'keyWordCategory', tagType: 'dict-select', dictCode: 'keyword_category', span: 8, toggle: false },
        { label: '状态', prop: 'state', tagType: 'dict-select', dictCode: 'enable_status', span: 8, toggle: false  },
        { label: '创建时间', prop: 'createTime', tagType: 'range-picker', format: 'YYYY-MM-DD', span: 8, toggle: false },
      ],
      columns: [
        { title: '序号', dataIndex: 'order', width: 60, align: 'center',
          customRender: (text, record, index) =>
            `${(this.pageFilter.pageNo - 1) * this.pageFilter.pageSize + (index + 1)}` //序号分页后连续
        },
        { title: '关键词', dataIndex: 'keyWordName', width: 100, align: 'left',
          customRender: (text) => {
            return <j-ellipsis value={text} length={12} />
          },
        },
        { title: '关键词级别', dataIndex: 'keyWordLevel', width: 80, align: 'center',
          customRender: text => {
            return this.$filterDictTextByCache('keyword_level', text)
          }
        },
        { title: '关键词类别', dataIndex: 'keyWordCategory', width: 80, align: 'center',
          customRender: text => {
            return this.$filterDictTextByCache('keyword_category', text)
          }
        },
        { title: '关键词描述', dataIndex: 'keyWordDescribe', width: 150, align: 'center',
          customRender: (text) => {
            return <j-ellipsis value={text} length={10} />
          }
        },
        { title: '状态', dataIndex: 'state', width: 50, align: 'center',
          customRender: text => {
            return  (
              <span class={text==1 ? 'text_color_1' : text==0 ? 'text_color_2' : ''}>
                {this.$filterDictTextByCache('enable_status', text)}
              </span>
            )
          }
        },
        { title: '创建时间', dataIndex: 'createTime', width: 110, align: 'center' },
        { title: '创建人', dataIndex: 'create', width: 80, align: 'center',
          customRender: (text, record, index) => {
            let realname = Object.keys(text).length>0 && text.realname? text.realname: ''
            return realname
          }
        },
        {
          title: '操作',
          width: 80,
          align: 'center',
          dataIndex: 'action',
          customRender: (text, record, index) => {
            return (
              <a-space size={6}>
                <a-button type="link" style={'padding:0'} onClick={event => this.clickPush(record)}>编辑</a-button>
                <a-button type="link" style={'padding:0'} onClick={event => this.handleOperate(record.state==1?'disable':'enable', record)}>
                  {record.state==1? '停用':'启用'}
                </a-button>
              </a-space>
            )
          }
        }
      ],
      fieldArrModal: [
        { label: '关键词', prop: 'keyWordName', tagType: 'input' },
        { label: '关键词级别', prop: 'keyWordLevel', tagType: 'dict-select', dictCode: 'keyword_level' },
        { label: '关键词类别', prop: 'keyWordCategory', tagType: 'dict-select', dictCode: 'keyword_category' },
        { label: '关键词描述', prop: 'keWordDescribe', tagType: 'textarea' },
      ],
      validatorRules: {
        keyWordName:[ { required: true, message: '请输入关键词!' }],
        keyWordLevel:[ { required: true, message: '请选择关键词级别!' }],
        keyWordCategory:[ { required: true, message: '请选择关键词类别!' },],
      },
      pageFilter: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData: {},
    }
  },
  async mounted() {
    this.onQuery()
  },
  methods: {
    onQuery() {
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      this.queryParam = {}
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.refreshTable()
    },
    onTableChange(pagination, pageFilter, sorter) {
      this.pageFilter = Object.assign({}, this.pageFilter, pagination)
      this.refreshTable()
    },
    refreshTable() {
      let {createTime, ...dataParam} = this.queryParam // 剔除createTime元素，dataParam最新的对象
      let queryParam = Object.assign({}, dataParam, this.pageFilter)
      this.loading = true
      alarmServiceApi
        .getKeywordList(queryParam)
        .then((res) => {
          if (res.success) {
            this.pageData = res.result ? res.result : {}
            this.loading = false
            this.$refs.table.onClearRowKeys()
          } else {
            this.loading = false
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    onSelectedRow(keys) {
      this.isDisabled = keys.length > 0 ? false : true;
    },
    // 业务操作-启用、停用
    handleOperate(type, record) {
      let selectList = this.$refs.table.getSelectedRows()
      let ids = selectList.map(item => item.keyWordId)
      let that = this
      let title, form = {}
      if (type=='enable') {
        title = '启用', form = { ids: record? [record.keyWordId] : ids, state: 1 }
      } else if(type=='disable') {
        title = '停用', form = { ids: record? [record.keyWordId] : ids, state: 0 }
      }
      this.$confirm({
        title: `确定${title}选中的数据？`,
        onOk() {
          alarmServiceApi.enableKeyword(form).then((res) => {
            if (res.success) {
              that.$message.success(res.message? res.message: `${title}操作成功！`)
              that.onQuery()
            } else {
              that.$message.warn(res.message? res.message: `${title}操作失败！`)
            }
          }).catch(e=>{
            that.$message.warn("操作失败！")
          })
        }
      })
    },
    // 获取组件的时间， prop为对应的字段，date为选中的时间值
    getChangeTime(prop, date) {
      if(prop === 'createTime') {
        this.$set( this.queryParam, 'createTimeStart', date[0] )
        this.$set( this.queryParam, 'createTimeEnd', date[1] )
      }
    },
    // 新建
    clickPush(record) {
      this.visible=true
      this.model = record? Object.assign({}, record, {keWordDescribe: record.keyWordDescribe}):{}
      this.title = record && Object.keys(record).length>0 && record.keyWordId? '编辑':'新增'
    },
    handleOk() {
      const parameter = Object.assign({}, this.model)
      this.$refs.subForm.validate((valid)=> {
        if (valid) {
          let api
          if(Object.keys(parameter).length>0 && parameter.keyWordId) {
            api = alarmServiceApi.updateKeyword(parameter)
          } else {
            api = alarmServiceApi.addKeyword(parameter)
          }
          if(!api) return
          api.then(res => {
            this.confirmLoading = false
            if (res.success) {
              this.$message.success(res.message)
              this.onQuery()
              this.handleCancel()
            } else {
              this.$message.warn(res.message)
            }
          })
          .catch(e => {
            this.$message.warn('请求失败！')
            this.confirmLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleCancel() {
      this.visible=false
      this.model = {}
    }
  }
}
</script>

<style scoped lang="less">
.text_color_1 {
  color: #70B603;
}
.text_color_2 {
  color: #d9001b;
}
</style>
